// pages/activedetial/activedetial.js
var WxParse = require("../../wxParse/wxParse.js");
var api = require("../../api.js"),
  app = getApp();
var r;
var mydata = {
  end: 0,
  replyUserName: ""
};
Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 2,
    classDetail: {},
    price: "",
    classList: [],
    consultes: [],
    isFolded: true,
    replyUserName: "",
    pageIndex: 2,
    popup: true,
    loadMoreJson: false,
    loadMore: false,
    videoPlay: null,
    video: true,
    popup1: true,
    showShare: true,
    inviteOpenId: '',
    play_time:0,
    /** 积分兑换提示框 */
    visible: false,
    actions: [
      { 
        name: '✔确认兑换',
        color: '#FFB02F'
      }
    ],
    /** 兑换课程需要的积分 */
    exchangePoints: 0,
    disabled:false
    // inviteOpenId: 'o15OP4qsu-fkXnrwkZy-w5Y5xW5g'
  },
  /**
   * 生命周期函数--监听页面加载
   *
   */
  onLoad: function(options) {
    r = this;
    /** 调用是否已授权的方法 */
    getApp().is_empower();
    var id = options.id;
    if (options.inviteOpenId) {
      r.setData({
        inviteOpenId: options.inviteOpenId
      })
    }
    r.setData({
      id: id,
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var _this = this;
    r.toast = _this.selectComponent("#toast");
    var userid = getApp().globalData.userInfo.openId;
    wx.showLoading({
      title: "数据加载中"
    });
    var t = new Object();
    (t.pageIndex = "1"), (t.pageSize = "5"), (t.couId = r.data.id);
    wx.request({
      url: api.cou.avos,
      data: t,
      success: function(res) {
        wx.hideLoading();
        r.setData({
          classList: res.data.data,
        });
        setTimeout(function() {
          const avoUrl = res.data.data[0].avoUrl;
          r.playVideo(avoUrl)
        }, 1500);
      }
    });
    var t = new Object();
    t.couId = _this.data.id;
    t.openId = getApp().globalData.wxUserInfo.openId;
    if (_this.data.inviteOpenId) {
      t.inviteOpenId = _this.data.inviteOpenId;
    }
    app.getData.couDetail(t).then(res => {
      if (res.code == 200) {
        setTimeout(function() {
          wx.hideLoading();
          const t = res.data;

          console.log(t)

          _this.setData({
            classDetail: t,
            exchangePoints: t.exchangePoints
          });
          /** 课程介绍处理 */
          const img = t.couDescription;
          t.couDescription = img.replace(/\<img/gi, '<img style="max-width:100%;height:auto;" ');
          
          if (_this.data.inviteOpenId) {
            r.setData({
              invite_img: t.invite_img,
              invite_name: t.invite_name,
              showShare: false,
            });
          }
          /** 已购买该课程 */
          if (t.is_redeemed == true)
          _this.setData({
            disabled: true
          });

        }, 1200);
      }
    });
  },
  change: function() {
    r.setData({
      isFolded: !r.data.isFolded,
    })
  },


  /************************************ 积分兑换 ************************************/

  /** 积分兑换 */
  exchange:function(){
    r.setData({  visible: true, })
  },
  /** 关闭弹框 */
  close_handle: function(){
    r.setData({ visible: false, })
  },
  /** 确认兑换 */
  handle_exchange: function(){
    const action = [...this.data.actions];
    action[0].loading = true;
    r.setData({ actions: action });
    var open_id = getApp().globalData.open_id;
    setTimeout(() => {
      action[0].loading = false;
      /** 请求后台积分兑换 */
      wx.request({
        url: api.cou.exchange_course,
        data: {
          open_id: open_id,
          cou_id: r.data.id,
          integral: r.data.exchangePoints,
        },
        success: function (res) {
          r.setData({ visible: false, actions: action });
          /** 兑换成功 */
          if (res.data.code == 200) {
            r.setData({
              disabled: true
            });
          }
          /** 积分不足，兑换失败 */
          if (res.data.code == 500) {
            console.log(res.data.msg)
          }
        }
      });
      
      
    }, 2000);
  },

  /************************************ 结束 ************************************/

  /** 用户点击右上角分享 */
  onShareAppMessage: function() {
    var openid = getApp().globalData.wxUserInfo.openId;
    return {
      title: r.data.classDetail.couTitle,
      path: `pages/index/index?id=${r.data.classDetail.couId}&shareType=2&inviteOpenId=${openid}`,
      success: function(res) {},
      fail: function(res) {}
    }
  },

  // 切换导航
  switchNav: function(e) {
    var cur = e.currentTarget.dataset.current;
    r.setData({
      currentTab: cur
    });
    if (cur == 2) {
      var t = new Object();
      (t.pageIndex = "1"), (t.pageSize = "5"), (t.couId = r.data.id);
      wx.request({
        url: api.cou.avos,
        data: t,
        success: function(res) {
          // console.log(res.data);
          setTimeout(function() {
            wx.hideLoading();
            r.setData({
              classList: res.data.data,
            });
          }, 1000);
        }
      });
    } else if (cur == 3) {
      // 获取评论列表
      var t = new Object();
      (t.pageIndex = "1"), (t.pageSize = "3"), (t.otherId = r.data.id);
      wx.request({
        url: api.detail.consultData,
        data: t,
        success: function(res) {
          if (res.statusCode == 200 && res.data.code == 200) {
            if (res.data.data.length > 0) {
              r.setData({
                consultes: res.data.data,
                loadMoreJson: true,
                loadMore: true
              });
            } else {
              r.setData({
                consultes: [],
                loadMoreJson: false,
                loadMore: false
              });
            }
          }
        }
      });
    }
  },
  /** 播放记录 */
  upd_play_record:function(e){
    // this.setData({
    //   play_time: e.detail.currentTime
    // });
    // console.log('当前播放时长 -- > ' + this.data.play_time)
  },
  /** 暂停播放 */
  pause:function(e){
    console.log('当前播放时长 -- > ' + this.data.play_time)
  },
  //提交评论
  replaySubmit: function(e) {
    var form = e.detail.value;
    var that = this;
    var user = getApp().globalData.wxUserInfo;
    var t = new Object();
    let conArea = form.conArea;
    if (conArea == "") {
      wx: wx.showToast({
        title: "内容为空"
      });
      return false;
    }
    (t.openId = user.openId), (t.otherId = r.data.id), (t.conArea = conArea), (t.type = 2);
    wx.request({
      url: api.detail.addConsult,
      data: t,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        console.log(res);
        if (res.statusCode == 200 && res.data.code == 200) {
          wx.showToast({
            title: "评论成功"
          });
          that.setData({
            popup: true
          });
          // 获取评论列表
          var t = new Object();
          var replayarr = [];
          (t.pageIndex = "1"), (t.pageSize = "3"), (t.otherId = that.data.id);
          wx.request({
            url: api.detail.consultData,
            data: t,
            success: function(res) {
              if (res.statusCode == 200 && res.data.code == 200) {
                if (res.data.data.length > 0) {
                  that.setData({
                    consultes: res.data.data,
                    // replayarr: replayarr
                  });
                } else {
                  that.setData({
                    consultes: res.data.data,
                  });
                }
              }
            }
          });
        } else {
          wx.showToast({
            title: res.data.msg
          });
        }
      }
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.showNavigationBarLoading(),
      console.log("下拉刷新"),
      this.onShow(),
      setTimeout(function() {
        wx.hideNavigationBarLoading(), wx.stopPullDownRefresh();
      }, 1500);
  },
  // 下拉加载咨询
  loadMore: function() {
    var t = new Object();
    var that = this;
    var replayarr = [];
    t.pageIndex = that.data.pageIndex;
    t.pageSize = "3";
    t.otherId = that.data.id;
    if (!that.data.loadMoreJson) {
      return;
    }
    wx.request({
      url: api.detail.consultData,
      data: t,
      success: function(res) {
        if (res.statusCode == 200 && res.data.code == 200) {
          if (res.data.data.length > 0) {
            that.data.pageIndex++;
            that.setData({
              loadMoreJson: true,
              consultes: that.data.consultes.concat(res.data.data)
            });
            console.log(that.data);
          } else {
            that.setData({
              loadMoreJson: false
            });
          }
        }
      }
    });
  },
  bindReply: function(e) {
    const conId = e.currentTarget.dataset.id;
    this.setData({
      // replyUserName: mydata.replyUserName,
      reply: true,
      popup1: false,
      conId: conId
    });
  },
  /* 隐藏弹窗 */
  hidePopup(flag = true) {
    this.setData({
      popup: flag
    });
  },
  modalinput: function() {
    this.hidePopup(false);
  },
  /** 播放视频 */
  videoPlay: function(e) {
    const playData = e.currentTarget.dataset;
    if (r.data.classDetail.isVip == 0 && r.data.disabled == false) {
      if (playData.index >= 1) {
        r.toast.showToast('该课程需积分兑换');
        return;
      };
    } else {
      r.playVideo(playData.url)
    }
  },
  playVideo(url) {
    r.setData({
      playUrl: url,
      video: false
    })
    //停止正在播放的视频
    var videoContextPrev = wx.createVideoContext("myVideo");
    videoContextPrev.stop();
    setTimeout(function() {
      //将点击视频进行播放
      var videoContext = wx.createVideoContext("myVideo");
      videoContext.play();
    }, 500)

  },

  //添加回复
  submitForm1(e) {
    console.log(e)
    var form = e.detail.value;
    var that = this;
    var t = new Object();
    let comment = form.comment;
    if (comment == "") {
      wx.showToast({
        title: "内容为空"
      });
      return false;
    }
    (t.conId = that.data.conId),
    (t.repArea = comment),
    wx.request({
      url: api.detail.addReply,
      data: t,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        console.log(res);
        if (res.statusCode == 200 && res.data.code == 200) {
          wx.showToast({
            title: "回复成功"
          });
          that.getConsultData();
          that.setData({
            popup: true
          });

        } else {
          wx.showToast({
            title: res.data.msg
          });
        }
      }
    });
  },
  //输出评价
  delReplay(e) {
    const conId = e.currentTarget.dataset.id;
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除当前评论',
      success: function(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          var t = new Object();
          t.conId = conId;
          wx.request({
            url: api.detail.delConsult,
            data: t,
            method: "POST",
            header: {
              "content-type": "application/x-www-form-urlencoded"
            },
            success: function(res) {
              if (res.statusCode == 200) {
                if (res.data.code == 200) {
                  r.toast.showToast('删除成功');
                  that.getConsultData();
                  that.setData({
                    popup: true
                  });
                }
              }
            }
          })
        } else if (res.cancle) {
          onsole.log('用户点击取消')
        }

      }

    })
  },
  cancleReply: function() {
    this.setData({
      // replyUserName: ,
      reply: false,
      popup1: true,
      conId: ''
    });
  },
  addCollection: function(e) {
    console.log(e)
    var that = this;
    const opeType = e.currentTarget.dataset.collection;
    const json = that.data.classDetail;
    const n = {
      openId: getApp().globalData.wxUserInfo.openId,
      otherId: json.couId,
      type: 2,
      opeType: opeType
    };
    if (opeType == 0) {
      n.img = json.couImage;
      n.title = json.couTitle;
    }
    wx.request({
      url: api.detail.add_del_Collection,
      data: n,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        if (res.statusCode == 200) {
          if (res.data.code == 200) {
            const tips = opeType == 0 ? '已收藏' : '已取消';
            r.setData({
              isCollection: opeType == 0 ? 1 : 0
            })
            r.toast.showToast(tips);
          }

        }
      }
    });
  },
  /**关闭视屏 */
  closeVideo() {
    //执行退出全屏方法
    var videoContext = wx.createVideoContext('myVideo', this);
    videoContext.exitFullScreen();
  },
  fullScreen(e) {
    var isFull = e.detail.fullScreen;
    //视屏全屏时显示加载video，非全屏时，不显示加载video
    this.setData({
      fullScreen: isFull
    })
  }

});